package org.lgiavedoni.android.franq.util.phone;

import java.util.ArrayList;
import java.util.List;

import org.lgiavedoni.android.franq.service.log.Logger;
import org.lgiavedoni.android.franq.service.phone.ContextService;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;

public class WifiUtil {

	private static WifiManager wifi;

	private static List<ScanResult> result = new ArrayList<ScanResult>();

	private static WifiManager getManager() {
		try {
			// Setup WiFi
			if (wifi == null && ContextService.inst.isApplicationContextLoaded()) {
				wifi = (WifiManager) ContextService.inst.getApplicationContext().getSystemService(ContextService.inst.getApplicationContext().WIFI_SERVICE);
			}
			return wifi;
		} catch (Exception ex) {
			Logger.inst.error(ex);
			return null;
		}
	}

	public static List<ScanResult> listWifiNetworks() {
		if (!ContextService.inst.isApplicationContextLoaded())
			return new ArrayList<ScanResult>();
		try {
			result.clear();

			// Register Broadcast Receiver
			BroadcastReceiver receiver = new BroadcastReceiver() {
				@Override
				public void onReceive(Context c, Intent intent) {
					result.addAll(getManager().getScanResults());
					synchronized (result) {
						result.notifyAll();
					}
				}

			};

			ContextService.inst.getApplicationContext().registerReceiver(receiver, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));

			boolean enabledBefore = getManager().isWifiEnabled();
			if (!enabledBefore) {
				turnON();
			}
			synchronized (result) {
				result.wait();
			}

			if (!enabledBefore) {
				turnOFF();
			}
			ContextService.inst.getApplicationContext().unregisterReceiver(receiver);

		} catch (InterruptedException ex) {
			Logger.inst.error(ex);
		}
		return result;
	}

	public static List<String> listWifiNetworksBSSID() {
		List<String> l = new ArrayList<String>();
		for (ScanResult sr : listWifiNetworks()) {
			l.add(sr.BSSID);
		}
		return l;
	}

	public static void turnON() {
		getManager().setWifiEnabled(true);
	}

	public static void turnOFF() {
		getManager().setWifiEnabled(false);
	}

}
